#coding:utf-8 
from PyQt4 import QtCore

from twisted.words.xish import domish
from twisted.python import log

from include.IqQuery import IqQuery


class KeepAlive(QtCore.QTimer):
        intervalTime = 60000
        def __init__(self,parent=None):
                super(KeepAlive,self).__init__(parent)
                self.__errors = 0
                self.setSingleShot(True)
                self.setInterval(self.intervalTime)
                self.timeout.connect(self.ping)
        @property
        def errors(self):
                return self.__errors
        @QtCore.pyqtSlot()
        def ping(self):
                iq = self.parent().pingAndWaitForResponse()
                iq.timeleft = 10000
                iq.send(self.parent().selfJid.full())
                @iq.timeout.connect
                @QtCore.pyqtSlot()
                def losePacket():
                        log.msg("Timeout.KeepAlive packet  lost!")
                        self.__errors+=1 
                        if self.__errors > 10:
                                self.parent().disconnect()
                                log.msg("Many packets lost. Do disconnect")
                        else:
                                self.start()
                @iq.response.connect
                @QtCore.pyqtSlot("PyQt_PyObject")
                def reply(xml):
                        log.msg("KeepAlive sucess response")
                        self.__errors = 0
                        self.start()
        
                

